﻿using AutoMapper;
using HelenServer.Migrator;
using HelenServer.UserCenter.Contracts;

namespace HelenServer.UserCenter.Dal;

[ServiceProvider(typeof(IDalMigrateService), SqlServerConstants.ProviderName)]
public class DalMigrateService : IDalMigrateService
{
    private readonly IRepo<UserCenterDbContext> _repo;
    private readonly IMapper _mapper;
    private readonly ILogger<DalMigrateService> _logger;

    public DalMigrateService(
        UserCenterDbContext context,
        IMapper mapper,
        ILogger<DalMigrateService> logger)
    {
        _repo = new Repo<UserCenterDbContext>(context);
        _mapper = mapper;
        _logger = logger;
    }

    public async Task<OperationResult<bool>> MigrateAsync(CancellationToken cancellationToken = default)
    {
        var ztContext = MigrateProvider.Context ?? throw new InvalidOperationException("请先调用MigrateProvider.ReadyToMigrate方法");

        try
        {
            #region Role
            var ztRoles = MigrateProvider.DbCache.ZtLangs.Where(n => n.Section == "roleList").ToList();
            ztRoles.RemoveAll(n => string.IsNullOrEmpty(n.Value));

            var roleEntities = ztRoles.Select(n => new Role { Name = n.Value });
            var roleResult = await _repo.AddRangeAsync(roleEntities, cancellationToken);

            _logger.LogInformation("Role完成迁移，插入{result}行数据", roleResult);
            #endregion

            #region Position        
            var ztGroups = MigrateProvider.DbCache.ZtGroups.ToList();
            var maxGroupId = MigrateProvider.DbCache.ZtGroups.Max(n => n.Id);

            var limit = ztRoles
                .Where(n => !MigrateProvider.DbCache.ZtGroups.Any(x => x.Role == n.Key))
                .Select((k, i) => new ZtGroup { Id = (uint)(maxGroupId + i + 1), Name = k.Value, Role = k.Key });

            ztGroups.AddRange(limit);

            var psEntities = _mapper.Map<IEnumerable<ZtGroup>, IEnumerable<Position>>(ztGroups);

            var psResult = await _repo.AddIdentityRangeAsync(psEntities, cancellationToken);

            _logger.LogInformation("Position完成迁移，插入{result}行数据", psResult);
            #endregion

            #region User
            var userEntities = _mapper.Map<IEnumerable<ZtUser>, IEnumerable<User>>(MigrateProvider.DbCache.ZtUsers);

            var userResult = await _repo.AddIdentityRangeAsync(userEntities, cancellationToken);
            #endregion

            #region Department
            var deptEntities = _mapper.Map<IEnumerable<ZtDept>, IEnumerable<Department>>(MigrateProvider.DbCache.ZtDepts);

            var deptResult = await _repo.AddIdentityRangeAsync(deptEntities, cancellationToken);
            #endregion            

            await UserCenterMigrateProfile.DisposeAsync();
        }
        catch (Exception ex)
        {
            return OperationResult<bool>.Failed(ex.Message);
        }

        return OperationResult<bool>.OK(true);
    }
}